<template>
	<!-- <page-meta>
    <navigation-bar
      title="nbTitle"
	  title-align="left" 
    />
  </page-meta> -->
	<view class=".container">
		<!-- 		<uni-nav-bar left-icon="contact-filled" leftWidth="100px" shadow="true" statusBar="true" >
		</uni-nav-bar> --><!-- style="width: 32px;height: 32px;" -->
		<map id="map" class=".container_map" :scale="scale" :show-location="true" :latitude="latitude"
			:longitude="longitude" @markertap="markertap" @regionchange="regionchange">
			<view class=".navBar" :style="{ height: iStatusBarHeight + 'px'}">
				<!-- <navigator url="/pages/home/index" animation-type="slide-in-right" animation-duration="300"
					hover-class="navigator-hover">
					<image class=".wodeImage" :style="{height:menuButtonHeight+'px',width:menuButtonHeight+'px'}"
						src="../../static/index/wode.png"></image>
				</navigator>
				<u--text :margin="'0rpx 0rpx 6rpx 230rpx'" bold="true" size="16" :lineHeight="menuButtonHeight+'px'" text="牛牛充电"></u--text> -->
				<view class=".wodeImage">
					<navigator url="/pages/home/index" animation-type="slide-in-right" animation-duration="300"
						hover-class="navigator-hover">
						<image :style="{height:menuButtonHeight+'px',width:menuButtonHeight+'px'}"
							src="../../static/index/wode.png"></image>
					</navigator>
				</view>
				<view class=".title">
					<view>
						<u--text bold="true" size="16" :lineHeight="menuButtonHeight+'px'" text="天聖充电"></u--text>
					</view>
				</view>
			</view>
			<view class=".containerWrapper">
				<!-- <view v-if="orderStatus == 0 || orderStatus == 1" class=".useOrder">
					<u-notice-bar :text="`您当前有${orderStatus == 0 ? '未完成':'未支付' }的订单`" mode="link" speed="100" 
					:url="`/pages/orders/order-use`"></u-notice-bar>
				</view> -->
				<view v-if="orderStatus == 0" class=".useOrder">
					<u-notice-bar :text="`您当前有未完成的订单`" mode="link" speed="100" url="/pages/orders/order-use"></u-notice-bar>
				</view>
				<view v-if="orderStatus == 1" class=".useOrder">
					<u-notice-bar :text="`您当前有未支付的订单`" mode="link" speed="100" url="/pages/orders/order-pay"></u-notice-bar>
				</view>				
				<view v-if="orderStatus == 0 || orderStatus == 1" class=".heardAd">
					<u-swiper :list="heardAdList" keyName="url" height="60"></u-swiper>
				</view>
				<view v-if="!(orderStatus == 0 || orderStatus == 1)" class=".heardAd2">
					<u-swiper :list="heardAdList" keyName="url" height="60"></u-swiper>
				</view>
				<view class=".scannButton">
					<button @click="scanCode" style="border-radius:10px;background-color:  #73de87;">
						<image class=".scannButtonImage" src="../../static/index/saoma.png"></image>
						扫码充电
					</button>
				</view>
				<view class=".dingWei" @click="merchantAroundAreaList">
					<image style="width: 100%;height: 100%;" src="../../static/index/dingwei.png"></image>
				</view>
				<view class=".keFu" @click="calling">
					<image style="width: 100%;height: 100%;" src="../../static/index/kefu.png"></image>
				</view>
			</view>
		</map>
		<com-map ref="commap"></com-map>
		<u-modal @confirm="modalConfirm" @cancel="modalCancel" :show="inputNoShow" title="未扫描到充电柜,请输入编码用电"
			showCancelButton='true'>
			<u--input placeholder="请输入商户名称" border="surround" v-model="cabinetNo"></u--input>
		</u-modal>
		<u-toast ref="uToast"></u-toast>
		<u-popup :show="popupShow" closeable="true" closeOnClickOverlay="true" @close="popupClouse">
			<view class=".popupContainer">
				<!-- address: "华夏科技大厦"
				endHour: "11:30:00"
				id: "1714846786160529410"
				locationPoint: {lng: 116.30399548810406, lat: 39.982316195826236}
				mode: 0
				name: "test"
				phone: "15093359880"
				pic: "https://cdbtest.oss-cn-beijing.aliyuncs.com/admin/merchant/1697686297163.png"
				profitRatio: 1
				startHour: "00:00:00"
				status: 0 -->

				<uni-section title="门店信息" type="line">
					<uni-card :title="merchantInfo.name"
						:sub-title="'营业时间:' + merchantInfo.startHour +' - '+ merchantInfo.endHour"
						:extra="merchantInfo.mode == 0 ? '可租借 可归还':'其他门店不可归还' " :thumbnail="merchantInfo.showPic">
						<u-row customStyle="margin-bottom: 10px">
							<u--text size="18"
								:text="merchantInfo.priceTemplate.amount+'元/'+merchantInfo.priceTemplate.unitNum + (merchantInfo.priceTemplate.unit == 0?'分钟':'小时') "></u--text>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u--text size="15" :text="merchantInfo.priceTemplate.info"></u--text>
						</u-row>
						<u-row justify="space-between" customStyle="margin-bottom: 10px">
							<u-col span="5">
								<u-button size="large" shape="circle" text="扫码用电" @click="scanCode"></u-button>
							</u-col>
							<u-col span="5">
								<u-button size="large" type="success" shape="circle" text="导航到店"
									@click="navToMerchant(merchantInfo.address,merchantInfo.locationPoint.lng,merchantInfo.locationPoint.lat)"></u-button>
							</u-col>
						</u-row>
					</uni-card>
				</uni-section>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';

	let map;
	let that;
	const markerIdMap = new Map();
	export default {
		data() {
			return {
				title: 'map',
				latitude: 39.909,
				longitude: 116.39742,
				iStatusBarHeight: 0,
				menuButtonHeight: 0,
				inputNoShow: false,
				cabinetNo: '',
				scale: 16,
				popupShow: false,
				merchantInfo: {},
				heardAdList: [{
					url: 'https://cdn.uviewui.com/uview/swiper/swiper2.png',
				}, {
					url: 'https://cdn.uviewui.com/uview/swiper/swiper3.png'
				}],
				orderStatus:-1,


			}
		},
		onLoad() {
			that = this;
			this.$refs.commap.setlocation()
			uni.getSystemInfo({
				success: (res) => {
					// 获取手机顶部状态栏的高度
					const statusBarHeight = res.statusBarHeight || 0;

					// 获取导航栏的高度（手机状态栏高度 + 胶囊高度 + 胶囊的上下间距）
					const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
					const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2;

					// 计算顶部图标距离
					const topIconDistance = statusBarHeight + navBarHeight;

					this.iStatusBarHeight = topIconDistance;
					this.menuButtonHeight = menuButtonInfo.height
					// 打印顶部图标距离
					console.log('顶部图标距离:', topIconDistance, this.menuButtonHeight);
				},
				fail: (err) => {
					console.error('获取系统信息失败:', err);
				},
			});
			
		},
		onShow() {
			console.log("----------------onshow-------------")
			this.refreshHandler();
		},
		onReady() {
			map = uni.createMapContext("map", this);
			this.merchantAroundAreaList();
		},
		computed: {
			//引入store全局变量
			...mapState(['mylocationState', 'mylocation','loginState'])
		},
		methods: {
			refreshHandler(){
				if(this.loginState){
					this.$http_api.ordersNoFinish({
					}).then((res) => {
						console.log("用户有未完成的订单:",res)
						that.orderStatus = res.status;
					})
				}
			},
			//导航到店
			navToMerchant: function(address, lng, lat) {
				this.$refs.commap.toMapAPP(address, lng, lat)
			},
			popupClouse: function() {
				this.popupShow = false;
			},
			markertap: async function(e) {
				const merchant = markerIdMap.get(e.detail.markerId);
				console.log("markertap:", e.detail.markerId, merchant);

				const priceTemplate = merchant.priceTemplate;
				console.log("priceTemplate", priceTemplate)
				if (!priceTemplate) {
					this.$refs.uToast.show({
						type: 'error',
						position: 'top',
						message: "该店铺未设置价格模板"
					})
				}
				this.popupShow = true;
				this.merchantInfo = {
					...merchant
				};
			},
			regionchange: function() {
				uni.$u.throttle(this.toNext, 3000);
				markerIdMap.clear();

				map.getCenterLocation().then(async centerLocation => {
					const markers = []
					markers.push({
						id: 9999999,
						latitude: centerLocation.latitude, //纬度
						longitude: centerLocation.longitude, //经度
						iconPath: '/static/index/center.png', //显示的图标
						width: 40, //宽
						height: 40, //高
					});

					const merchantList = await this.$http_api.merchantAroundArea({
						lat: centerLocation.latitude,
						lng: centerLocation.longitude
					});
					console.log("merchantList :", merchantList)
					for (let i = 0; i < merchantList.length; i++) {
						const item = merchantList[i];
						const serverLonLat = this.$util.wgs84ToGcj102(item.locationPoint.lng, item
							.locationPoint.lat)

						markers.push({
							id: i + 1,
							latitude: serverLonLat[1], //纬度
							longitude: serverLonLat[0], //经度
							iconPath: '/static/index/map_cdb.png', //显示的图标
							width: 40, //宽
							height: 40, //高
						});
						markerIdMap.set(i + 1, item);
					}

					console.log("markers:", markers);
					map.addMarkers({
						markers,
						clear: true,
						complete(res) {
							console.log('addMarkers', res)
						}
					})

				});


			},
			calling: function() {
				let phoneNumber = '15093359880';
				console.log('==phoneNumber===', phoneNumber)
				uni.makePhoneCall({
					phoneNumber: phoneNumber,
					success: function() {
						console.log("拨打电话成功！")
					},
					fail: function() {
						console.log("拨打电话失败！")
					}
				})
			},
			scanCode() {
				this.popupShow = false;
				// 允许从相机和相册扫码
				uni.scanCode({
					success: async (res) => {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);

						const params = res.result.split("?")[1];
						//获取第一个参数值
						const cabinetNo = params.split("&")[0].split("=")[1];
						console.log("scanCode cabinetNo:", cabinetNo)
						const cabinetInfo = await this.$http_api.merchantCabinetInfo({
							cabinetNo: cabinetNo
						});
						if (!cabinetInfo) {
							uni.$u.toast('未扫码到充电柜,请联系客服');
							return;
						}

						uni.navigateTo({
							url: '/pages/mianya/mianya?cabinetNo=' + cabinetNo
						});


					},
					fail: (res) => {
						this.inputNoShow = true;
					}
				});
			},
			async modalConfirm() {
				if (this.cabinetNo) {
					this.inputNoShow = false;

					const cabinetInfo = await this.$http_api.merchantCabinetInfo({
						cabinetNo: this.cabinetNo
					});
					if (!cabinetInfo) {
						return;
					}
					// const merchantInfo = await this.$http_api.merchantInfo({
					// 	name: this.catinetName
					// });
					// if (!merchantInfo) {
					// 	return;
					// }
					uni.navigateTo({
						url: '/pages/mianya/mianya?cabinetNo=' + this.cabinetNo
					});

				} else {
					this.$refs.uToast.show({
						type: 'error',
						position: 'top',
						message: "请输入正确的充电柜编号"
					})
				}
			},
			modalCancel() {
				this.inputNoShow = false;
			},
			merchantAroundAreaList() {
				//判断定位状态
				if (!this.mylocationState) {
					this.$refs.commap.setlocation()
					return
				} else {
					console.log('已经获取定位')
					this.latitude = this.mylocation.latitude
					this.longitude = this.mylocation.longitude
				}
				const result = this.$util.wgs84ToGcj102(this.longitude, this.latitude)
				console.log('getLocation transform', result);
				map.moveToLocation({
					longitude: result[0],
					latitude: result[1],
					complete: function(res) {
						console.log('移动完成:', res)
					},
					fail: function(res) {
						console.log('移动完成fail:', res)
					}
				});
			},
		}
	}
</script>

<style>
	@import "./index.css";
	@import "./popup.css";
</style>